package com.ywl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ywl.entity.Comment;
import com.ywl.entity.HouseDetail;
import com.ywl.entity.Orders;
import com.ywl.mapper.CommentMapper;
import com.ywl.service.CommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ywl.service.HouseDetailService;
import com.ywl.service.OrderService;
import com.ywl.utils.MyStringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ywl
 * @since 2022-08-26
 */
@Service
@Slf4j
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {
    @Autowired
    private OrderService orderService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 根据id获取评论分页信息
     * @param detailId
     * @param commentPage
     * @return
     */
    @Override
    public Page<Comment> getPage(Long detailId, Page<Comment> commentPage) {
        LambdaQueryWrapper<Comment> qw = new LambdaQueryWrapper<>();
        qw.eq(Comment::getDetailId,detailId);
        super.page(commentPage, qw);
        return commentPage;
    }

    /**
     * 保存评论
     * @param orderId 房屋id
     * @param feelback
     * @return
     */
    @Override
    /*@CacheEvict(value = "orderCache",allEntries = true)*/
    @Transactional
    public boolean saveComment(Long orderId, String feelback) {
        //1.通过订单id，查询到对应订单，并对订单中的评论状态进行修改
        Orders orders = orderService.getById(orderId);
        orders.setCommentState(2);//更改订单评论状态
        orderService.updateById(orders);
        /*String key = "orderCache::order_"+orders.getPhone();
        redisTemplate.delete(key);*/

        //2.通过房屋id，获取到phone，并修改phone，进行字符串的替换操作，使用replace完成即可
        Long detailId = orders.getDetailId();
        String phone = orders.getPhone();
        Integer commentState = orders.getCommentState();
        String newPhone = phone.replace(phone.substring(3,7),"****");
        log.info("phone={}",newPhone);

        //3.新建Comment对象，设置对应的属性，并保存即可
        Comment comment = new Comment();
        comment.setDetailId(detailId);//设置房屋id
        comment.setOrderId(orderId);//设置订单id
        comment.setUsername(newPhone);//用户手机号
        comment.setComment(feelback);//设置评论
        comment.setStar(3);//星级


        boolean save = super.saveOrUpdate(comment);
        return save;
    }
}
